package xyz.xtt.user.validator;

import java.util.Arrays;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * @author huqibo
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {
	public static final String STRING = ",";
	private static final String DELIMITER = ", ";
	private static final String ALLOW_STR = "允许的取值: ";
	private String[] stringValues;
	private long[] longValues;
	private int[] intValues;
	private String message;

	@Override
	public void initialize(EnumValue constraintAnnotation) {
		this.stringValues = constraintAnnotation.stringValues();
		this.longValues = constraintAnnotation.longValues();
		this.intValues = constraintAnnotation.intValues();
		this.message = constraintAnnotation.message();
	}

	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
		// 处理 null 值（可根据需求定义）
		if (value == null) {
			return true;
		}

		boolean isValid = false;

		if (value instanceof String) {
			isValid = Arrays.asList(stringValues).contains(value);
		} else if (value instanceof Long) {
			isValid = Arrays.stream(longValues).anyMatch(v -> v == (Long) value);
		} else if (value instanceof Integer) {
			isValid = Arrays.stream(intValues).anyMatch(v -> v == (Integer) value);
		}

		if (!isValid) {
			// 构建动态错误消息
			StringBuilder suggestedValues = new StringBuilder();
			suggestedValues.append(value).append("不是有效的取值,");
			if (stringValues.length > 0) {
				suggestedValues.append(ALLOW_STR).append(String.join(DELIMITER, stringValues));
			}
			if (longValues.length > 0) {
				suggestedValues.append(ALLOW_STR).append(Arrays.toString(longValues));
			}
			if (intValues.length > 0) {
				suggestedValues.append(ALLOW_STR).append(Arrays.toString(intValues));
			}
			context.disableDefaultConstraintViolation();
			context.buildConstraintViolationWithTemplate(message + STRING + suggestedValues)
					.addConstraintViolation();
		}
		return isValid;
	}

}